// routes/cards/findAllByGroup.js
const express = require('express');
const pool = require('../../config/pool'); // 使用连接池
const router = express.Router();
const hadLogin = require('../../middleware/hadLogin');

router.post('/', hadLogin, (req, res) => {
    const user_id = req.user_id;
    const { card_id, card_account, card_password } = req.body;
    const queryCard = `SELECT * FROM cards where id =?`;
    pool.query(queryCard, [card_id], (err, results) => {
        if (err) {
            return res.json({
                code: 0,
                message: '数据库错误',
                success: false
            });
        }
        if (results.length == 0) {
            return res.json({
                code: 0,
                message: '卡片不存在',
                success: false
            });
        }
        const card = results[0];
        if(card.is_active != 1) {
            return res.json({
                code: 0,
                message: '卡片已被禁用',
                success: false
            });
        } 
        const total_amount = (card.face_value*card.redemption_discount)/100;
        const query = `INSERT INTO orders (user_id, card_id, card_account, card_password, total_amount) VALUES (?,?,?,?,?)`;
        pool.query(query, [user_id, card_id, card_account, card_password, total_amount], (err, results) => {
            if (err) {
                return res.json({
                    code: 0,
                    message: '数据库错误',
                    success: false
                });
            }
            res.json({
                code: 1,
                message: '订单创建成功',
                success: true,
                data: {
                    order_id: results.insertId,
                    total_amount: total_amount
                }
            });
        });
    })
});

module.exports = router;